from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
from django.conf import settings
import logging

def get_alipay_client():
    """
    获取支付宝客户端实例
    """
    # 配置日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(levelname)s %(message)s',
        filemode='a',
    )
    logger = logging.getLogger('')

    # 创建支付宝客户端配置
    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = settings.ALIPAY_GATEWAY
    alipay_client_config.app_id = settings.ALIPAY_APPID
    alipay_client_config.app_private_key = settings.APP_PRIVATE_KEY
    alipay_client_config.alipay_public_key = settings.ALIPAY_PUBLIC_KEY
    alipay_client_config.charset = settings.ALIPAY_CHARSET
    alipay_client_config.sign_type = settings.ALIPAY_SIGN_TYPE

    # 创建支付宝客户端
    client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)
    return client

def get_alipay_url(order_number, total_amount, subject):
    """
    生成支付宝支付链接
    """
    client = get_alipay_client()

    # 构建支付请求模型
    model = AlipayTradePagePayModel()
    model.out_trade_no = order_number
    model.total_amount = str(total_amount)
    model.subject = subject
    model.product_code = "FAST_INSTANT_TRADE_PAY"

    # 创建支付请求
    request = AlipayTradePagePayRequest(biz_model=model)
    request.notify_url = settings.ALIPAY_NOTIFY_URL
    request.return_url = settings.ALIPAY_RETURN_URL

    # 执行请求获取响应
    response = client.page_execute(request, http_method="GET")
    return response

def verify_alipay_notification(data, signature):
    """
    验证支付宝异步通知
    """
    client = get_alipay_client()
    return client.verify(data, signature)
